/**
 * Copyright (C) 2018 - 2020 https://github.com/LeeYan9
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.bifrost.service.impl;

import com.bifrost.entity.MerchantShipment;
import com.bifrost.entity.MerchantStore;
import com.bifrost.model.vo.PageVO;
import com.bifrost.repository.MerchantShipmentRepository;
import com.bifrost.service.StoreShipmentService;
import com.google.common.collect.Lists;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.persistence.criteria.*;
import java.util.ArrayList;

/**
 * @author Lee
 * Create Class on 2018/8/30
 * @com.bifrost.service.impl
 * @wechat-mall
 */
@Service
public class StoreShipmentServiceImpl implements StoreShipmentService {

    @Autowired
    MerchantShipmentRepository storeShipmentRepository;

    @Override
    public PageVO page(Integer page, Integer size, MerchantStore merchantStore, String type) {

        PageRequest pageRequest = new PageRequest(page - 1, size);
        Specification<MerchantShipment> specification = new Specification<MerchantShipment>() {
            @Override
            public Predicate toPredicate(Root<MerchantShipment> root, CriteriaQuery<?> query, CriteriaBuilder cb) {

                ArrayList<Predicate> predicates = Lists.newArrayList();
                Join<MerchantShipment, MerchantStore> store = root.join("merchantStore", JoinType.INNER);
                predicates.add(cb.equal(store.get("merchantId"),merchantStore.getMerchantId()));

                if(StringUtils.isNotBlank(type)){
                    predicates.add(cb.equal(root.get("type"),type));
                }
                return cb.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };

        Page<MerchantShipment> shipmentPage = storeShipmentRepository.findAll(specification, pageRequest);
        Assert.notEmpty(shipmentPage.getContent(),"门店没有运费模板信息");

        return new PageVO(page,size,(int)shipmentPage.getTotalElements(),shipmentPage.getContent());
    }
}
